package trystero.lib.component.parser;

import java.util.Vector;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONTokener;

import trystero.lib.component.TagList;
import trystero.lib.component.ReaderTag;

public class TagListParser
{
   InputStream stream;

   public TagListParser(InputStream stream)
   {
      this.stream = stream;
   }

   public TagList parse() throws Exception
   {
      JSONTokener t = new JSONTokener(new InputStreamReader(this.stream));
      JSONObject o = new JSONObject(t);
      return this.parse(o);
   }

   public TagList parse(JSONObject o) throws Exception
   {
      TagList ids = new TagList();

      JSONArray tags = (JSONArray)o.get("tags");
      ids.tags(this.parseTagVector(tags));

      return ids;
   }

   public Vector parseTagVector(JSONArray a) throws Exception
   {
      Vector v = new Vector();

      for(int i = 0; i < a.length(); i++)
      {
	 ReaderTag tag = this.parseTag((JSONObject)a.get(i)); 
	 v.add(tag);
      }

      return v;
   }

   public ReaderTag parseTag(JSONObject o) throws Exception
   {
      ReaderTag tag = new ReaderTag();

      tag.tag((String)o.get("id"));
      tag.sortid((String)o.get("sortid"));

      return tag;
   }
}
